import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';

/// 基于库logger进行二次封装的日志打印调试类
///
/// @Methods v; d; i; w; e;
class LogUtil {
  static const bool colors = kReleaseMode ? false : true;

  static final Logger _logger = Logger(
    printer: PrefixPrinter(PrettyPrinter(
      stackTraceBeginIndex: 1, // 方法栈的开始下标
      methodCount: 2, // 打印方法栈的个数
      errorMethodCount: 8, // 自己传入方法栈对象后该参数有效
      lineLength: 100, // 每行最多打印的字符个数
      colors: colors, // 日志是否有颜色
      printEmojis: false, // 是否打印 emoji 表情
      printTime: false, // 是否打印时间
      // noBoxingByDefault: true // 是否打印无框
    )),
    output: CustomOutput(),
    filter: ConsoleFilter()
  );

  static void v(dynamic message) {
    _logger.v(message);
  }

  static void d(dynamic message) {
    _logger.d(message);
  }

  static void i(dynamic message) {
    _logger.i(message);
  }

  static void w(dynamic message) {
    _logger.w(message);
  }

  static void e(dynamic message) {
    _logger.e(message);
  }

  static void wtf(dynamic message) {
    _logger.wtf(message);
  }
}

class ConsoleFilter extends LogFilter {
  @override
  bool shouldLog(LogEvent event) {
    var shouldLog = false;
    assert(() {
      if (event.level.index >= level!.index) {
        shouldLog = true;
      }
      return true;
    }());
    if (isRealese()) {
      return event.level.index >= Level.info.index;
    }
    return shouldLog;
  }
}

/// 统一判断是否是release
bool isRealese() {
  return kReleaseMode;
}

/// 去除颜色ANSI编码
String removeColorAnsi(String msg) {
  if (LogUtil.colors) {
    // 匹配 ANSI 编码的正则表达式
    RegExp regExp = RegExp('\x1B\\[[0-9;]*[m|K]');
    return msg.replaceFirst(regExp, "").replaceFirst(AnsiColor.ansiDefault, "");
  } else {
    return msg;
  }
}

/// 自定义输出
/// 
/// 增加在release模式下将日志写入文件
class CustomOutput extends ConsoleOutput {
  @override
  void output(OutputEvent event) {
    super.output(event);
    if (isRealese()) {
      _writeToFile(event);
    }
  }

  Directory? _directory;
  late IOSink _sink;

  /// 日志信息写入文件
  void _writeToFile(event) async {
    String filePath = await _getFilePath();
    
    File file = File(filePath);

    if (!file.existsSync()) {
      //文件不存在后，重写获取指向新文件的句柄
      file.create();
    }
    _sink = file.openWrite(
      mode: FileMode.writeOnlyAppend,
    );

    //这里避免_sink未初始化
    // _sink.writeAll(event.lines.map((item)=> removeColorAnsi(item)), '\n');
    _sink.writeAll(event.lines, '\n');
    _sink.writeln();
    _sink.close();
  }

  final DateFormat dateFormat = DateFormat('yyyy-MM-dd');

  /// 获取日志文件路径，文件名为当前日期
  Future<String> _getFilePath() async {
    // // /data/user/0/com.example.app_demo/cache
    // _directory ??= await getTemporaryDirectory();
    // // /data/user/0/com.example.app_demo/files
    // _directory ??= await getApplicationDocumentsDirectory();
    if (Platform.isIOS) {
      // /data/user/0/com.example.app_demo/app_flutter
      _directory ??= await getApplicationSupportDirectory();
    } else if (Platform.isAndroid) {
      // /storage/emulated/0/Android/data/com.example.my_app/files
      _directory ??= await getExternalStorageDirectory();
    }

    // List<FileSystemEntity> fList = _directory!.listSync();
    // for (var fItem in fList) {
    //   if (fItem is File) {
    //     print(fItem.lastModifiedSync());
    //   }
    // }

    String today = dateFormat.format(DateTime.now());
    String? id = await _getPhoneId();

    return "${_directory!.path}/${id != null ? "$id$today" : today}.txt";
  }

  Future<String?> _getPhoneId() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if(Platform.isAndroid){
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      return androidInfo.id.toString();
    }else{
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      return iosInfo.utsname.machine;
    }
  }
}
